package com.gcxy.shop.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gcxy.shop.common.CommonException;
import com.gcxy.shop.domain.User;
import com.gcxy.shop.service.UserService;
@WebServlet(urlPatterns="/register.do")
public class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Logger logger=LoggerFactory.getLogger(getClass());
	private UserService userService=new UserService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("开始执行dopost");
		try {
		
		//抽取参数
		   String usercode=request.getParameter("usercode");
		   String username=request.getParameter("username");
		   String password=request.getParameter("password");
		   String confirm=request.getParameter("confirm");
		   User user=new User(username,usercode,password);//封装一个对象
		   logger.debug("抽取参数成功，{}，{},{}",usercode,username,password);
		//数据转换
		//数据校验
		   if(usercode!=null&&usercode.length()>=4
				   &&username!=null&&username.length()>=1
				   &&password!=null&&password.length()>=6
				   &&confirm!=null&&confirm.length()>=6
				   &&password.equals(confirm)) {	
				}
				else {
					throw new CommonException("您注册的信息有误");	
				}
		//业务方法处理
		   userService.register(user);
		//转发与重定向
		   response.sendRedirect(request.getContextPath()+"/login.jsp");
		   logger.debug("注册成功");	
	} catch (Exception e) {
		logger.error(e.getMessage());
		request.setAttribute("error", e.getMessage());
		request.getRequestDispatcher("/register.jsp").forward(request, response);
	}
	
    
	}
}
